package webservices.sbe;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.cb.common.util.ConfigUtil;
import com.travelsky.sbeclient.SBEClient;
import com.travelsky.sbeclient.SBEResponse;
import com.travelsky.sbeclient.authorization.AccountActiveRequest;
import com.travelsky.sbeclient.authorization.AuthorizationRequest;
import com.travelsky.sbeclient.authorization.AuthorizationResponse;
import com.travelsky.sbeclient.exceptions.SBEClientException;
import com.travelsky.sbeclient.utils.Constants;
import com.travelsky.sbeclient.utils.SBEUtil;

@Service
public class APITokenServices {

	private static Logger logger = Logger.getLogger(APITokenServices.class);
	private static String token;

	public  String getToken() {
		return token;
	}

	public void createService(SBEClient client) {
		String accountId = ConfigUtil.getInstance().getXmlValByStr("travelsky.userId", "mysltest01");
		String pswd=ConfigUtil.getInstance().getXmlValByStr("travelsky.pswd", "mysltest01");
		String accountPwd = SBEUtil.md5(pswd);
		// 激活账号
		try {
			// 激活账号
			activeAccount(client, accountId, accountPwd, "1");
			applyToken(client, accountId, accountPwd);
		} catch (SBEClientException sbe1) {
			// 如果是重复激活，忽略
			if (sbe1.getErrorCode() == Constants.RESULT_CODE_ERROR_ACCOUNT_ALREADY_ACTIVED) {
				logger.warn("account has on work!");
				try {
					AccountActiveRequest request = holdAccount(client,
							accountId, accountPwd, "1");
					inActiveAccount(client, request);
				} catch (SBEClientException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				applyToken(client, accountId, accountPwd);
			}
			// 如果不是重复激活，后面就不能用了，记录日志
			else {
				logger.warn("Fail to active account!");
				return;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 管理账号
	 * 
	 * @param client
	 * @param 账号
	 * @param 密码
	 * @param 1激活 0挂机
	 * @throws SBEClientException
	 */
	private void activeAccount(SBEClient client, String ID, String PW,
			String isActive) throws SBEClientException {

		AccountActiveRequest aaRequest = new AccountActiveRequest(ID, PW,
				isActive);

		// 激活账号
		if (isActive.equals("1")) {
			client.activeAccount(aaRequest);
		}
		// 挂机账号
		else {
			// @TODO没有实现连接池心跳的情况下权宜之计
			SBEResponse response = client.inactiveAccount(aaRequest);
			if (response.getResultCode() == Constants.RESULT_CODE_ERROR_TCP_RECONNECT_SUCCEED) {
				client.inactiveAccount(aaRequest);
			}
		}

	}

	private void inActiveAccount(SBEClient clinet, AccountActiveRequest request)
			throws SBEClientException {
		clinet.activeAccount(request);
	}

	/**
	 * 挂起帐号
	 * 
	 * @param client
	 * @param ID
	 * @param PW
	 * @param isActive
	 * @throws SBEClientException
	 */
	private AccountActiveRequest holdAccount(SBEClient client, String ID,
			String PW, String isActive) throws SBEClientException {
		AccountActiveRequest aaRequest = new AccountActiveRequest(ID, PW,
				isActive);
		SBEResponse response = client.inactiveAccount(aaRequest);
		if (response.getResultCode() == Constants.RESULT_CODE_ERROR_TCP_RECONNECT_SUCCEED) {
			client.inactiveAccount(aaRequest);
		}
		return aaRequest;
	}

	/**
	 * 初始化sbeClient
	 */
	private void applyToken(SBEClient client, String id, String pw) {

		// 申请令牌
		AuthorizationRequest aRequest = new AuthorizationRequest(id, pw);
		try {
			logger.warn("Start to apply token!");
			SBEResponse applyTokenResponse = client.applyToken(aRequest);

			// 申请令牌成功，把令牌保存起来
			if (applyTokenResponse.getResultCode() == Constants.RESULT_CODE_SUCCEED) {
				logger.warn("Apply token successful!");
				token = ((AuthorizationResponse) applyTokenResponse).getToken();
			}

		} catch (SBEClientException se) {
			logger.warn("failed to apply token!" + "error code_:_"
					+ se.getErrorCode() + "_error msg_:_" + se.getErrorMsg());
		}
	}
}
